from django.template.loader import render_to_string
from django import template

register = template.Library()

def render_breadcrumb(parser, token):
    try:
        tag_name, page, template_name = token.split_contents()
    except ValueError:
        try:
            template_name = '"pages/breadcrumb.html"'
            tag_name, page = token.split_contents()
        except ValueError:
            raise template.TemplateSyntaxError, "%r tag requires one ore two arguments" % token.contents.split()[0]
    
    return BreadcrumbRenderer(page, template_name)

class BreadcrumbRenderer(template.Node):
    def __init__(self, page, template_name):
        self.page = template.Variable(page)
        self.template_name = template.Variable(template_name)
        
    def render(self, context):
        request = template.Variable('request').resolve(context)
        
        try:
            template_name = self.template_name.resolve(context)
            page = self.page.resolve(context)
            path = page,
            
            while (page.parent):
                path.append(page.parent)
                page = page.parent
        except (template.VariableDoesNotExist):
            return ''
            
        c = template.RequestContext(request, {
            'path': path,
            'page': page
        })
        
        return render_to_string(template_name, c)
        
register.tag('breadcrumb', render_breadcrumb)